package org.grc.app.z_project.z_framework.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 
 * 序列化工具类
 * 
 * @author grc
 * @since 1.0-SNAPSHOT
 */
public class SerializableUtil {

	private static final Logger logger = LoggerFactory.getLogger(SerializableUtil.class);

	private static String basePath = "serializable";

	static {
		mkdir();
	}
	
	/**
	 * 序列化
	 */
	public static void writeObject(Object o){
		String filePath = basePath + "/" + o.getClass().getName();
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
			out.writeObject(o);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("对象序列化出错", e);
			e.printStackTrace();
		}
	}
	/**
	 * 反序列化
	 */
	@SuppressWarnings("unchecked")
	public static <T> T readObject(Class<T> clazz){ 
		String filePath = basePath + "/" + clazz.getName();
		T t = null;
		try {
			ObjectInputStream oin = new ObjectInputStream(new FileInputStream(filePath));
			t = (T) oin.readObject();

			oin.close();
		} catch (IOException | ClassNotFoundException e) {
			logger.error("反序列化出错", e);
			e.printStackTrace();
		} 
		return t;
	}
	
	public static void mkdir(){
		File baseDir =new File(basePath);    
		//如果不存在Serializable文件夹就创建    
		if  (!baseDir .exists()  && !baseDir .isDirectory())      
		{       
//			logger.info(baseDir + "//不存在");  
			baseDir .mkdir();
		} else   
		{  
//			logger.info(baseDir + "//目录存在");  
		} 
	}
	
	private static void deleteFile (Class<?> clazz){
		String filePath = basePath + "/" + clazz.getName();
		File file = new File(filePath);

		if(file.exists())
		{
			file.delete();
		}
	}
	
	private static boolean ifExistsSerializableFile(Class<?> clazz){
		String filePath = basePath + "/" + clazz.getName();
		File file = new File(filePath);
		if(file.exists())
		{
			return true;
		}

		return false;
	}

	private static void createSerializableFileIfNotExists(Class<?> clazz){
		String filePath = basePath + "/" + clazz.getName();
		File file = new File(filePath);
		if(!file.exists())
		{
			try {
				ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
				out.flush();
				out.close();
			} catch (IOException e) {
				logger.error("创建序列化文件出错", e);
				e.printStackTrace();
			} 
		}
	}
	
	private static Object getObject(Class<?> clazz){ 
		Object object = null;
		if(ifExistsSerializableFile(clazz))
		{
			object = readObject(clazz);
		}
		else
		{
			createSerializableFileIfNotExists(clazz);
			try {
				object = clazz.newInstance();
			} catch (InstantiationException | IllegalAccessException e) {
				e.printStackTrace();
			}
			writeObject(object);
		}
		return object;
	}
}
